import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Modal } from 'antd';
import { ExclamationCircleOutlined, CloseOutlined, SmallDashOutlined } from '@ant-design/icons';
import { ConnectProps, ConnectState } from '@/models/connect';

import Avatar from './AvatarDropdown';
import styles from './index.less';

export type SiderTheme = 'light' | 'dark';
export interface GlobalHeaderRightProps extends ConnectProps {
    dispatch: Dispatch<any>;
    tabs: any[];
    showMore: boolean;
    location: any;
}

class GlobalHeaderRight extends React.Component<GlobalHeaderRightProps> {
    tabDom: any = null;

    handleOpenJumpDialog = (path: string) => {
        const currentUrl = window.location.pathname;
        if (currentUrl.indexOf('/add') > 0 || currentUrl.indexOf('/edit') > 0) {
            Modal.confirm({
                title: '警告！',
                icon: <ExclamationCircleOutlined />,
                content: '您可能有修改尚未保存，确定要跳转吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => this.handleJump(path),
            });
        } else {
            this.handleJump(path);
        }
    };

    handleJump = (path: string) => {
        router.push(path);
    };

    handleClose = (url: string, event: any) => {
        event.stopPropagation();

        const { dispatch, tabs, location } = this.props;
        const index = tabs.findIndex((tab: any) => tab.url === url);
        tabs.splice(index, 1);

        const currentUrl = location.pathname + (location.search ? `${location.search}` : '');

        if (tabs.length === 0) {
            window.location.href = '/';
        } else if (currentUrl === url) {
            if (tabs[index]) {
                if (tabs[index - 1]) {
                    router.push(tabs[index - 1].url);
                } else {
                    router.push(tabs[index].url);
                }
            } else {
                router.push(tabs[tabs.length - 1].url);
            }
        } else {
            router.push(currentUrl);
        }

        dispatch({
            type: 'global/resetTab',
            payload: { tabs },
        });
    };

    handleShowMore = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'global/setMore',
            payload: { isShow: true },
        });
    };

    componentDidCatch(error: any, info: any) {
        if (error) {
            window.location.reload();
        }
    }

    renderTabElem = (tab: any) => {
        const { location } = this.props;
        const currentUrl = location.pathname + (location.search ? location.search : '');

        return (
            <div
                key={tab.url}
                className={styles.tabBox}
                style={{ background: currentUrl === tab.url ? 'antiquewhite' : 'aliceblue' }}
            >
                <div
                    className={styles.title}
                    title={tab.name}
                    onClick={() => this.handleOpenJumpDialog(tab.url)}
                >
                    {tab.name}
                </div>

                <CloseOutlined
                    className={styles.close}
                    onClick={this.handleClose.bind(this, tab.url)}
                />
            </div>
        );
    };

    renderTabListElems = (tabs: any[]) => <>{tabs.map(tab => this.renderTabElem(tab))}</>;

    renderMoreListElems = (tabs: any[]) => {
        const { showMore } = this.props;
        return (
            <div className={styles.moreBox}>
                <SmallDashOutlined
                    className={styles.moreChar}
                    onClick={this.handleShowMore}
                />
                {showMore && (
                    <div className={styles.moreList}>
                        {tabs.map(tab => (
                            <div className={styles.item} key={tab.url}>
                                {this.renderTabElem(tab)}
                            </div>
                        ))}
                    </div>
                )}
            </div>
        );
    };

    render() {
        const { tabs } = this.props;

        let maxCount = 0;
        let showTabs = [];
        let moreTabs = [];
        if (this.tabDom) {
            maxCount = Math.floor(this.tabDom.clientWidth / 120) - 1;
            [showTabs, moreTabs] = [tabs.slice(0, maxCount), tabs.slice(maxCount)];
        }

        return (
            <div className={styles.right}>
                <div
                    className={styles.tabList}
                    ref={node => { this.tabDom = node; }}
                >
                    {showTabs.length > 0 && this.renderTabListElems(showTabs)}
                    {moreTabs.length > 0 && this.renderMoreListElems(moreTabs)}
                </div>
                <div className="avatar">
                    <Avatar menu />
                </div>
            </div>
        );
    }
}

export default connect(({ global }: ConnectState) => ({
    tabs: global.tabs,
    showMore: global.showMore,
}))(GlobalHeaderRight);
